//
//  SuperViewController.m
//  ICrEAM
//
//  Created by mac on 16/10/14.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "SuperViewController.h"
#import "UITableView+factory.h"
#import "DeviceMacro.h"
#import "SuspendView.h"
#import "SubMenu.h"
#import "GetCarViewController.h"
#import "NavRightView.h"
#import "MBProgressHUD+MJ.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "ICFileViewController.h"
#import "SetupViewController.h"
#import "AppDelegate.h"
#import "ICMCustomerAndCarViewController.h"
#import "RepairHistoryViewController.h"
#import "ICMMaintenanceProjectListViewController.h"
#import "ICMRepairPartsListViewController.h"
#import "ICMAppointmentResearchViewController.h"
#import "ICMTomorrowPrepareViewController.h"
#import "AppointmentViewController.h"
#import "ICMGetCarSearchViewController.h"
#import "ProxyViewController.h"
#import "ICMBalanceResearchViewController.h" //结算

#import "FinishCheckedViewController.h"
#import "MororcadeViewController.h"//车间进度
#import "RepaircadeViewController.h"
@interface SuperViewController ()<NavRightViewDelegate>
@property(nonatomic,strong)NSMutableDictionary *frames;


@end

@implementation SuperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.hideSuspendView=YES;
    if ([self isMemberOfClass:[MainViewController class]]   ) {
        self.suspendView.y=100;
    }
    else{
        self.suspendView.y=0;
    }
    
    self.edgesForExtendedLayout=UIRectEdgeNone;
    [self setWhiteNavBar];
    [self setNavRightItem];
    [self navigationLeftItem];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(vinandonw:) name:@"vinandonw" object:nil];
    
    
}
//接车单查询预览传值
-(void)vinandonw:(NSNotification*)aNotification{
    
    self.super_owner_no = aNotification.userInfo[@"OWNER_NO"];
    self.super_VIN = aNotification.userInfo[@"VIN"];
    
    
}

/**
 *  导航左按钮
 */
- (void)navigationLeftItem{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed: @"back_item"] forState:UIControlStateNormal];
    leftBtn.frame = CGRectMake(0, 0, 20, 20);
    [leftBtn addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = item;
    
}
-(void)backButtonClick{
    
    [self.navigationController popViewControllerAnimated:YES];
//     [self.navigationController popToRootViewControllerAnimated:YES];
    
    
}
#pragma mark 设置导航栏右按钮
-(void)setNavRightItem{
    NavRightView *customView=[NavRightView createNavRightView];
    customView.delegate=self;
    self.navigationItem.rightBarButtonItem=self.hideRightNavItem?nil:[[UIBarButtonItem alloc]initWithCustomView:customView];
}
//个人信息
-(void)didClickUserInfo{
    if(!self.super_owner_no)
        self.super_owner_no = @"";
    if(!self.super_VIN)
        self.super_VIN = @"";
    if (IsStrEmpty(self.super_owner_no) || IsStrEmpty(self.super_VIN)) {
        return;
    }
    
    
    [self superGetInfoWithOWNER_NO:self.super_owner_no orVin:self.super_VIN type:@"0"];
    
}





//获取车主车辆信息
- (void)superGetInfoWithOWNER_NO:(NSString *)OWNER_NO orVin:(NSString *)vin type:(NSString *)type{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:OWNER_NO forKey:@"OWNER_NO"];
    [parameters setObject:vin forKey:@"VIN"];
    [manager startGetRequestWithURL:QueryOwnerDetail parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        ICMCustomerAndCarViewController *customerAndCar = [ICMCustomerAndCarViewController new];
        if(IsArr(data[@"TM_OWNER"]))
        {
            customerAndCar.personerModel = [ICMPersonerModel yy_modelWithDictionary:data[@"TM_OWNER"][0]];
            
            
            
        }
        if(IsArr(data[@"TM_VEHICLE"]))
        {
            customerAndCar.carModel = [ICMCarModel yy_modelWithDictionary:data[@"TM_VEHICLE"][0]];
            customerAndCar.personerModel.adviserCode = data[@"TM_VEHICLE"][0][@"SERVICE_ADVISOR"];
            customerAndCar.personerModel.adviserName = data[@"TM_VEHICLE"][0][@"EMPLOYEE_NAME"];
            
        }
        
        
        customerAndCar.entrance = [type integerValue];
        
        
        if (IsStrEmpty(self.super_owner_no) || IsStrEmpty(self.super_VIN)) {
            return;
        }
        //跳转
        [self.navigationController pushViewController:customerAndCar animated:YES];
        
    }];
    
}

//搜索维修历史
-(void)didClickRepairHistory{
    
    RepairHistoryViewController *historyViewController = [[RepairHistoryViewController alloc]init];
    if(self.super_VIN && ![self.super_VIN isEqualToString:@""])
    {
        [historyViewController superSearchWithKeyword:self.super_VIN];
    }
    else
    {
        if(self.super_owner_no && ![self.super_owner_no isEqualToString:@""])
        {
            [historyViewController superSearchWithKeyword:self.super_owner_no];
        }
    }
    [self.navigationController pushViewController:historyViewController animated:YES];
    
}
//搜索项目
-(void)didClickSearchProject{
    ICMMaintenanceProjectListViewController *vc = [[ICMMaintenanceProjectListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
//搜索零件
-(void)didClickSearchParts{
    
    ICMRepairPartsListViewController *partsViewController = [[ICMRepairPartsListViewController alloc]init];
    [self.navigationController pushViewController:partsViewController animated:YES];
}
#pragma mark 文件查询
-(void)didClickSearchDirectory{
        [self.view endEditing:YES];
    //    [self.navigationController popToRootViewControllerAnimated:NO];
    //    MainViewController *main=[AppDelegate mainViewController];
    ICFileViewController *file=[[ICFileViewController alloc]init];
    [self.navigationController pushViewController:file animated:YES];
}

#pragma mark 设置按钮点击
-(void)didClickSetup{
    [self.view endEditing:YES];
    SetupViewController *alterSetUpCtr=[[SetupViewController alloc]init];
    alterSetUpCtr.isTop=YES;
    __weak typeof(alterSetUpCtr) weakInner=alterSetUpCtr;
    [alterSetUpCtr setDismissBlock:^{
        
        [weakInner removeFromParentViewController];
    }];
    [ alterSetUpCtr showOnView:[[UIApplication sharedApplication] keyWindow]];
    [self addChildViewController:alterSetUpCtr];
}
#pragma mark 返回首页
-(void)didbackHomePage{
    //预约，接车，委托书，结算 判断是否数据变动
    if(self.super_hasViewValueChanged)
    {
        [self alertMessage:@"是否放弃当前数据？"  withSuccessBlock:^{
            self.super_hasViewValueChanged = NO;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        return;
    }
    
     [self.view endEditing:YES];
    if ([ICrEAMUser shareICrEAMUser].checkIsEdit) {
        [self alertMessage:@"是否放弃终检"  withSuccessBlock:^{
            [ICrEAMUser shareICrEAMUser].checkIsEdit=NO;
          [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        return;
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.view bringSubviewToFront: self.suspendView];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:self.hideNav animated:animated];
    [self.view bringSubviewToFront:self.suspendView];
    self.suspendView.hidden=self.hideSuspendView;
}

#pragma mark 悬浮按钮
-(SuspendView *)suspendView{
    if (!_suspendView) {
        _suspendView=[[SuspendView alloc]initWithFrame:CGRectMake(ScreenWidth-35, 100, 35, 68)];
        if ([ICrEAMUser shareICrEAMUser].userType==WorkshopType) {
            _suspendView.buttonNumber=1;
        }else{
            _suspendView.buttonNumber=8;
        }
        [self.view addSubview: _suspendView];
    }
    return _suspendView;
    
}

#pragma mark---配置导航条颜色－－－
- (void)setupTitleColor
{
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
}


- (void)setWhiteNavBar
{
    //    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    // 设置导航条－白色属性
    //    [self settingNavBarImage];
}

- (void)settingNavBarImage
{
    NSString * navBarImageName;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:navBarImageName] forBarMetrics:UIBarMetricsDefault];
    //    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:navBarImageName]]];
}



- (void)clearLeftNavBarItem
{
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationItem.leftBarButtonItem = nil;
}

- (TPKeyboardAvoidingTableView *)tpTableView
{
    if(!_tpTableView)
    {
        
        _tpTableView = [TPKeyboardAvoidingTableView tableView];
        
        _tpTableView.delegate =self;
        
        _tpTableView.dataSource =self;
        
    }
    return _tpTableView;
}
- (UITableView *)tableView{
    
    if(!_tableView){
        
        _tableView = [UITableView tableView];
        
        _tableView.delegate =self;
        
        _tableView.dataSource =self;
    }
    
    return _tableView;
}
#pragma mark 切换view
-(PTYSwitch *)mySwitch{
    if (!_mySwitch) {
        _mySwitch= [[PTYSwitch alloc] initWithStringsArray:self.switchArray];
        
        _mySwitch.sliderColor = [UIColor clearColor];
        _mySwitch.backgroundColor =[UIColor clearColor];
        if ([ICrEAMTool isVW]) {
            _mySwitch.sliderBottomColor = RGB(53, 165, 255);
            _mySwitch.labelTextColorInsideSlider = TitleColor_Blue;;
        }else{
            _mySwitch.sliderBottomColor = KSKBgColor;
            _mySwitch.labelTextColorInsideSlider = KSKBgColor;;
        }
        _mySwitch.labelTextColorOutsideSlider =[UIColor blackColor];
        _mySwitch.backgroundTopColor = [UIColor clearColor];
        _mySwitch.backgroundBottomColor = [UIColor colorWithHexString:@"#c4c4c4"];
        _mySwitch.seperateColor = [UIColor clearColor];
        _mySwitch.backgroundColor=RGB(230, 236, 236);
        _mySwitch.labelTextFont = [UIFont fontWithName:@"HelveticaNeue" size:kSearchFont];
        _mySwitch.cornerRadius = 0;
        _mySwitch.sliderOffset = 0;
    }
    return _mySwitch;
}
#pragma mark 搜索框
-(MySearchView *)searchTextField{
    if (!_searchTextField) {
        _searchTextField=[[MySearchView alloc]init];
        _searchTextField.backgroundColor=[UIColor whiteColor];
        _searchTextField.font=[UIFont systemFontOfSize:14];
        _searchTextField.layer.cornerRadius=18;
        _searchTextField.delegate=self;
        _searchTextField.layer.masksToBounds=YES;
        _searchTextField.autocapitalizationType=UITextAutocapitalizationTypeAllCharacters;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.isSearch=YES;
        _searchTextField.textAlignment=NSTextAlignmentLeft;
    }
    return _searchTextField;
}
#pragma mark 显示提示信息
-(void)showText:(NSString *)loadtext{
    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hud];
    hud.mode = MBProgressHUDModeText;
    hud.labelText =loadtext;
    [hud show:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        hud.hidden=YES;
        [hud removeFromSuperview];
    });
}
#pragma mark  悬浮按钮跳转其他控制器（判断是否在编辑状态）
-(void)CheckIsEdit:(BOOL)isEdit pushType:(NSInteger)type{
    if (isEdit) {
        [self alertMessage:@"是否放弃终检"  withSuccessBlock:^{
            [ICrEAMUser shareICrEAMUser].checkIsEdit=NO;
            [self pushSuspendMenuWithType:type];
        }];
        return;
    }else{
        [self pushSuspendMenuWithType:type];
    }
}
#pragma mark  悬浮按钮跳转
-(void)pushSuspendMenuWithType:(NSInteger)tag{
    switch (tag)
    {
        case 8:{
            
            if ([ICrEAMUser shareICrEAMUser].userType==WorkshopType) {
                //用户权限是车间主管时跳转车间进度看板
                MororcadeViewController *appointmentViewController=[MororcadeViewController new];
                appointmentViewController.hideRightNavItem=YES;
                [self.navigationController pushViewController:appointmentViewController animated:YES];
                
            }else{
 #pragma mark 维修进度看板
                RepaircadeViewController *repaircadeViewController=[RepaircadeViewController new];
                [self.navigationController pushViewController:repaircadeViewController animated:YES];
                
            }
            
        }
            break;
            
        case 9:{
#pragma mark 车间进度看板
            MororcadeViewController *appointmentViewController=[MororcadeViewController new];
            
            [self.navigationController pushViewController:appointmentViewController animated:YES];
            
        }
            break;
        case 10:{//创建预约单
            
            AppointmentViewController *appointmentViewController=[AppointmentViewController new];
            
            [self.navigationController pushViewController:appointmentViewController animated:YES];
        } break;
        case 11:{
#pragma mark 预约查询
            ICMAppointmentResearchViewController *appointmentViewController=[ICMAppointmentResearchViewController new];
            
            [self.navigationController pushViewController:appointmentViewController animated:YES];
        } break;
        case 2://准备
        {
            ICMTomorrowPrepareViewController *tommorowViewController=[ICMTomorrowPrepareViewController new];
            
            [self.navigationController pushViewController:tommorowViewController animated:YES];
            
        }
            break;
        case 14://接车
            
            [self.navigationController pushViewController:[GetCarViewController new] animated:YES];
            
            break;
        case 15:
#pragma mark 接车单查询
            [self.navigationController pushViewController:[ICMGetCarSearchViewController new] animated:YES];
            
            break;
        case 4:
#pragma mark 委托书查询
            [self.navigationController pushViewController:[ProxyViewController new] animated:YES];
            break;
        case 5:
#pragma mark 终检查询
            [self.navigationController pushViewController:[FinishCheckedViewController new] animated:YES];
            break;
        case 6:
#pragma mark 结算查询
            [self.navigationController pushViewController:[ICMBalanceResearchViewController new] animated:YES];
            break;
        case 7:{
 #pragma mark 文件查询
            ICFileViewController *file=[[ICFileViewController alloc]init];
            [self.navigationController pushViewController:file animated:YES];
        } break;
        default:
            break;
    }
}
- (UITableView *)groupTableView{
    
    if(!_groupTableView){
        
        if (IOS7_OR_LATER) {
            _groupTableView = [UITableView groupTableView];
        }else{
            _groupTableView = [UITableView tableView];
        }
        
        _groupTableView.delegate =self;
        
        _groupTableView.dataSource =self;
        
    }
    
    return _groupTableView;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return ((interfaceOrientation ==UIDeviceOrientationLandscapeLeft)||(interfaceOrientation ==UIDeviceOrientationLandscapeRight));
    
}

- (BOOL)shouldAutorotate
{
    return YES;
}


-(void)requestDataWithAction:(RequestBaseApi *)action haveHud:(BOOL)haveHud showError:(BOOL)isShow success:(YTKRequestCompletionBlock)success    failure:(YTKRequestCompletionBlock)failure{
    if (haveHud) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    [action startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        ResponseBase *res=[ResponseBase mj_objectWithKeyValues:request.responseJSONObject];
        if (res.CODE==-1) {
            NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
            for (int i = 0; i < [cookies count]; i++) {
                NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
                
            }
            LoginViewController *login=[[LoginViewController alloc]init];
            [AppDelegate currentAppDelegate].window.rootViewController= login;
            return ;
        }
        if (res.CODE!=200) {
            [self showText:res.MSG];
            return;
        }
        if (success) {
            success(request);
        }
    } failure:^(__kindof YTKBaseRequest *request) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if (!isShow) {
            [self showText:@"网络异常"];
        }
        if (failure) {
            failure(request);
        }
    }];
    
}
#pragma mark  弹出提示信息
-(void)alertMessage:(NSString *)message withBlock:(ICrEAMBlock)successBlock{
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (successBlock) {
            successBlock();
        }
    }];

    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark  弹出提示信息
-(void)alertMessage:(NSString *)message withSuccessBlock:(ICrEAMBlock)successBlock{
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (successBlock) {
            successBlock();
        }
    }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark  弹出提示信息有取消事件的
-(void)carChangeAlertMessage:(NSString *)message withSuccessBlock:(ICrEAMBlock)successBlock failBlock:(ICrEAMBlock)failBlock{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (successBlock) {
            successBlock();
        }
    }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (failBlock) {
            failBlock();
        }
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];



}
-(void)alertMessage:(NSString *)message withSuccessBlock:(ICrEAMBlock)successBlock failBlock:(ICrEAMBlock)failBlock{
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (successBlock) {
            successBlock();
        }
    }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (failBlock) {
            failBlock();
        }
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"vinandonw" object:nil];

}
@end
